<template>
  <el-dialog :title="title" @closed="methods.closed" width="50%" ref="dialog" v-model="dialogVisable">
    <el-form :model="props.model" :rules="rules" ref="form" label-position="top" :disabled="props.editType === 'view'">
      <el-form-item label="Key" prop="roleKey">
        <el-input v-model="props.model.roleKey"></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="roleName">
        <el-input v-model="props.model.roleName"></el-input>
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model="props.model.sort"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="props.model.remark"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="methods.save" :icon="ButtonIcons.finish" v-if="props.editType !== 'view'">
          提交
        </el-button>
        <el-button @click="methods.close" :icon="ButtonIcons.close">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { SysRole } from '~/types/sys/SysRole'
import { EditType, EditTypeText } from '~/types/ui/EditType'
import { RoleService } from '~/service/sys'
import elpUtil from '~/utils/elp'
import { ButtonIcons } from '~/components/xview/button'
import { ref, computed, watch } from 'vue'
import msgUtil from '~/utils/message'
import { ITreeNode } from '~/types/ui/tree/ITreeNode'

const form = elpUtil.refs.form()
const dialog = elpUtil.refs.dialog()

const dialogVisable = ref(false)

const props = withDefaults(
  defineProps<{
    editType: EditType
    model: SysRole
    visable: boolean
  }>(),
  {
    show: false,
    editType: 'view',
    visable: false
  }
)

const title = computed(() => {
  return EditTypeText[props.editType] + '角色'
})

const rules = ref({
  roleKey: [
    {
      required: true,
      message: '名称必须录入'
    }
  ],
  roleName: [
    {
      required: true,
      message: '角色Key必须录入'
    }
  ]
})

const emits = defineEmits(['closed', 'saved', 'update:visable'])

watch(() => props.visable, (val) => {
  dialogVisable.value = val
})
watch(dialogVisable, (val) => {
  emits('update:visable', val)
})

const methods = {
  closed() {
    form!.value.clearValidate()
    emits('closed')
  },
  close() {
    dialogVisable.value = false;
  },
  save() {
    form!.value.validate(async (result: boolean) => {
      if (!result) {
        msgUtil.warning('验证错误，请检查输入信息')
        return
      }
      if (props.editType === 'insert') {
        await RoleService.insert(props.model)
      } else {
        await RoleService.update(props.model)
      }
      emits('saved')
      dialogVisable.value = false
    })
  }
}
</script>
